package com.symone.webcms.util;

import com.symone.webcms.model.base.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class TreeUtil<T extends TreeNode> {

    /**
     * 两层循环实现建树
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public List<T> bulid(List<T> treeNodes) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (treeNode.getPid() == 0) {
                trees.add(treeNode);
            }
            for (T it : treeNodes) {
                if (it.getPid().equals(treeNode.getId()) ) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<T>());
                    }
                    treeNode.getChildren().add(it);
                }
            }
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     * @param treeNodes
     * @return
     */
    public List<T> buildByRecursive(List<T> treeNodes) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (treeNode.getPid() == 0 ) {
                trees.add(findChildren(treeNode,treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    public T findChildren(T treeNode,List<T> treeNodes) {
        treeNode.setChildren(new ArrayList<T>());

        for (T it : treeNodes) {
            if(treeNode.getId().equals( it.getPid()) ) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<T>());
                }
                treeNode.getChildren().add(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }

}
